package packag04;

import com.ynny.bean.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class CourseDaoImpl implements CourseDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void updateCourse(String courseName) {
        String sql = "update course set " + courseName + "=" +courseName +"-1";
        int num = jdbcTemplate.update(sql);
        if (num <= 0){
            System.out.println("更新失败");
        }
    }
    @Override
    public void queryCourse() {
        String sql = "select * from course";
        RowMapper<Course> rowMapper = new BeanPropertyRowMapper<Course>(Course.class);
        Course course = jdbcTemplate.queryForObject(sql,rowMapper);
        System.out.println(course);
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false,
            isolation = Isolation.DEFAULT)

    public void selectCourse(String number, String courseName) {
        updateCourse(courseName);
        queryCourse();
        jdbcTemplate.execute("create table if not exists optional_course("
                + "number varchar(20),courseName varchar(20),score double)");
        String sql = "insert into optional_course(number,courseName,score) values(?,?,?)";
        jdbcTemplate.update(sql,number,courseName,0);
        System.out.println("查寻选课记录");
        sql = "select * from optional_course where number=?";
        List<Course> maps = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Course>(Course.class),number);
        for (Course map : maps) {
            System.out.println(map);
        }
    }

    @Override
    public void selectCourseWithTransaction(String number, String courseName) {

    }
}
